package com.lishe.lishe.lishe.module.mall.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.mall.adapter.MallGoodsAdapter;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.module.mall.bean.SkuObject;
import com.lishe.lishe.lishe.module.mall.fragment.GoodsDetailFragent;
import com.lishe.lishe.lishe.module.mall.fragment.GoodsDetailFragmentWeb;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.module.me.activity.AddAddrActivity;
import com.lishe.lishe.lishe.module.me.bean.AddressItem;
import com.lishe.lishe.lishe.module.me.http.HttpUserCenter;
import com.lishe.lishe.lishe.module.shopingcart.activity.ShoppingCartActivity;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.lishe.lishe.lishe.widget.SelectAddressPopupwindow;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.util.TextUtils;

/**
 * Created by lwa on 2017/9/20.
 * 商品详情，及单品的总页（底部弹窗的实现页面）
 */

public class MallGoodsActivity extends BaseActivity implements View.OnClickListener {
    private Button callBack;
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private MallGoodsAdapter mallGoodsAdapter;
    private LinkedList<String> titles = new LinkedList<>();
    private LinkedList<Fragment> fragments = new LinkedList<>();
    private String itemId;
    private Button add;
    private LinkedList<String> lisAddress = new LinkedList<>();
    private List<AddressItem> address_list;
    private List<SkuObject> skus = new ArrayList<>();
    private ImageView goods_cart;
    private TextView goods_count;

    private String addressID;
    private String skuId;
    private int count;
    private MallGoods mallGoods;
    private SelectAddressPopupwindow.Builder pop;
    public static final int INSTOCK = 0;//下架
    public static final int ONSALE = 1;//在售
    public static final int NOGOODS = 2;//库存不足

    public static void jump(Activity activity, String itemId) {
        Intent intent = new Intent(activity, MallGoodsActivity.class);
        intent.putExtra("itemId", itemId);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        itemId = getIntent().getStringExtra("itemId");
        setContentView(R.layout.activity_mall_goods);
        mallGoodsAdapter = new MallGoodsAdapter(getSupportFragmentManager(), fragments, titles);
        initFragment();
        initView();
        regisBrocastReciver();
    }

    private void initFragment() {
        titles.clear();
        fragments.clear();
        titles.add("单品");
        titles.add("详情");
        fragments.add(GoodsDetailFragent.newInstance(itemId));
        fragments.add(GoodsDetailFragmentWeb.newInstance(itemId));
    }

    private void initView() {
        viewPager = findViewById(R.id.viewPager);
        callBack = findViewById(R.id.callBack);
        viewPager.setAdapter(mallGoodsAdapter);
        tabLayout = findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
        add = findViewById(R.id.add);
        goods_cart = findViewById(R.id.goods_cart);
        goods_count = findViewById(R.id.goods_count);
        setlistener();
        getAddress();
    }

    private void setlistener() {
        callBack.setOnClickListener(this);
        add.setOnClickListener(this);
        goods_cart.setOnClickListener(this);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.e("position", position + "");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.callBack:
                finish();
                break;
            case R.id.add:
                if (TextUtils.isEmpty(Globals.getToken())) {
                    //如果未登录登录，跳到登录界面
                    doCheckLoginIfNeedAndRedirectAuth(MallGoodsActivity.this);
                    return;
                }
                mallGoods = ((GoodsDetailFragent) fragments.get(0)).getMallObject();
//                if ("instock".equals(mallGoods.getApprove_status())) {
//                    toast("商品已下架");
//                    return;
//                }
                if(mallGoods==null||mallGoods.getShop_id() == null){
                    return;
                }

                if (mallGoods.getShop_id().equals("32")) {//等于32说明为全球购商品
                    toast(getString(R.string.not_support_global_goods));
                    return;
                }
                createPopupWindow(mallGoods);
                break;
            case R.id.goods_cart:
                ShoppingCartActivity.jump(MallGoodsActivity.this, true);
                break;
        }
    }

    /**
     * 获取收货地址
     */
    private void getAddress() {
        HttpUserCenter.getAddressList(null, response);
    }

    /**
     * 获取收货地址
     */
    private void checkSKU() {
        String msg;
        if (mallGoods == null) {
            mallGoods = ((GoodsDetailFragent) fragments.get(0)).getMallObject();
        }
        if (addressID == null) {
            msg = "请添加或选择地址";
            toast(msg);
            return;
        }
        if (skuId == null) {
            msg = "选择商品规格！";
            toast(msg);
            return;
        }
        LoadingUtils.createLoadingDialog(this, "正在检测库存...", true);
        HttpMall.checkSKU(Globals.getToken(), addressID, skuId, mallGoods.getShop_id(), mallGoods.getItem_id(), checkSkuResponse);
    }

    /**
     * 添加购物车
     */
    private void addShoppingCart() {//注意此处的skuId不一定是mallGoods.getSkuid()
        if (mallGoods == null) {
            mallGoods = ((GoodsDetailFragent) fragments.get(0)).getMallObject();
        }
        LoadingUtils.closeDialog();
        Log.e("address--", addressID);
        LoadingUtils.createLoadingDialog(this, "正在添加到购物车...", true);
        HttpMall.addShoppingCart(Globals.getToken(), mallGoods.getItem_id(), skuId, count + "", mallGoods.getShop_id(), mallGoods.getJd_ids(), addressID, addShoppingCartResponse);
    }

    /**
     * 添加到购物车
     */
    AsyncHttpResponseHandler addShoppingCartResponse = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            Log.e("添加购物车", result);
            try {
                JSONObject json = new JSONObject(result);
                String msg = json.optString("msg");
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    pop.dissmiss();
                    toast(json.optString("data"));
                } else {
                    LoadingUtils.closeDialog();
                    toast(msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast(getString(R.string.network_or_server_exception));
            LoadingUtils.closeDialog();
        }
    };

    /**
     * 检测库存
     */
    AsyncHttpResponseHandler checkSkuResponse = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            Log.e("检测库存", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject dataObject = json.optJSONObject("data");
                    if (dataObject.optInt("status") > 0) {
                        addShoppingCart();
                    } else {
                        toast(dataObject.optString("message"));
                    }
                } else {
                    LoadingUtils.closeDialog();
                    String msg = json.optString("msg");
                    toast("检测库存，" + msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            LoadingUtils.closeDialog();
            toast(getString(R.string.network_or_server_exception));
        }
    };

    /**
     * 获取地址列表
     */
    LSWebHelper.WebCallBack response = new LSWebHelper.WebCallBack() {
        @Override
        public void onSuccess(JSONObject dataJson, String dataString, String message) {
            LoadingUtils.closeDialog();
            String data = dataString;
            Log.e("地址信息", data);
            address_list = JSON.parseArray(dataString, AddressItem.class);
            lisAddress.clear();
            if (address_list != null && address_list.size() >= 0) {
                for (AddressItem addressItem : address_list) {
                    String address = addressItem.getArea() + addressItem.getAddr();
                    lisAddress.add(address);
                }
            }
            if (isUp == true) {
                isUp = false;
                createPopupWindow(mallGoods);
            }
        }


        @Override
        public void onFailure(String message) {
            Toast.makeText(MallGoodsActivity.this, message, Toast.LENGTH_SHORT).show();
            LoadingUtils.closeDialog();
        }
    };

    /**
     * 加入购物车-popupwindow
     */
    private void createPopupWindow(final MallGoods mallGoods) {
        int defalutColor = getResources().getColor(R.color.gray_6);
        int selectColor = getResources().getColor(R.color.white);
        skus.clear();
        skus.addAll(((GoodsDetailFragent) fragments.get(0)).getSkus());
        pop = new SelectAddressPopupwindow.Builder(this, defalutColor, selectColor);
        pop.setName(mallGoods.getTitle());
        pop.setDiscountIntegral((int) ((float) mallGoods.getPrice() * 100));
        pop.setImgUrl(mallGoods.getImage_default_id());
        pop.addItem(lisAddress);
        pop.setSku(skus);
        pop.setIntegral((int) ((float) mallGoods.getMkt_price() * 100));
        pop.setOnItemOnclickListener(new SelectAddressPopupwindow.Builder.ItemOnclickListener() {
            @Override
            public void onAddressItemOnclickListener(boolean isAdd, String address0, int position) {
                Log.e("地址", address0);
                if (isAdd) {
                    addressID = null;
                    AddAddrActivity.jumpForResult(MallGoodsActivity.this, Globals.REQUSE_CODE_AddAddrActivity, 1, null);
                } else {
                    addressID = address_list.get(position).getArea_id();
                }
            }

            @Override
            public void onSkuItemOnclickListener(boolean isDefalut, String skuId0) {
                if (isDefalut) {
                    skuId = mallGoods.getSku_id();
                } else {
                    skuId = skuId0;
                }
            }

            @Override
            public void onAdd_RedusOnclickListener(int index, int count, TextView view) {
                Log.e("加减", index + "--" + count + "--");
            }

            //确定
            @Override
            public void onComfitOnclickListener(int count0) {
                count = count0;
                checkSKU();
                getGoodsCount();
            }
        });

        pop.create();
        pop.showAtLocation(add, Gravity.BOTTOM, -10, -10);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Globals.REQUSE_CODE_AddAddrActivity) {
                getAddress();
            }
        }
    }

    private void getGoodsCount() {
        HttpMall.getGoodsCountFromShoppingCart(Globals.getToken(), getGoodsCountRespose);
    }

    /**
     * 商品数量
     */
    AsyncHttpResponseHandler getGoodsCountRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            Log.e("购物车商品数量", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject data = json.optJSONObject("data");
                    int num = data.optInt("num");
                    if (num > 0) {
                        goods_count.setText(num + "");
                        goods_count.setVisibility(View.VISIBLE);
                    } else {
                        goods_count.setVisibility(View.GONE);
                    }
                } else {
                    goods_count.setVisibility(View.GONE);
                    LoadingUtils.closeDialog();
                    JSONObject msgObject = json.optJSONObject("msg");
                    String msgString = StringUtils.unicodeToString("msg", msgObject.toString());
                    Log.e("商品", "" + msgString);
                    if (msgString != null && msgString.contains("请登录")) {
                        toast("还未登录，无法获取购物车信息！");
                    } else {
                        toast("获取购物车信息，" + msgString);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast(getString(R.string.network_or_server_exception));
        }
    };

    //-----------------------------选择地址广播处理-----------------------------
    boolean isUp = false;

    private void regisBrocastReciver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Globals.ACTION_UPADDRESS);
        registerReceiver(receiver, intentFilter);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Globals.ACTION_UPADDRESS)) {
                Log.e("收到广播", "哈哈更新UI");
                pop.dissmiss();
                isUp = true;
                getAddress();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (!LSWebHelper.getInstance().isUserLogined()) {
            goods_cart.setVisibility(View.GONE);
        } else {
            goods_cart.setVisibility(View.VISIBLE);
            getGoodsCount();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 底部购物车按钮的改变
     */
    public void chageTate(final int status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status == INSTOCK) {//下架
                    add.setText("商品已下架");
                    add.setBackground(getResources().getDrawable(R.drawable.selector_btn_gray));
                    add.setEnabled(false);
                } else if (status == NOGOODS) {//库存不足
                    add.setText("库存不足");
                    add.setBackground(getResources().getDrawable(R.drawable.selector_btn_gray));
                    add.setEnabled(false);
                } else if (status == ONSALE) {//在售
                    add.setText("加入购物车");
                    add.setBackground(getResources().getDrawable(R.drawable.selector_btn_red));
                    add.setEnabled(true);
                }
            }
        });
    }
}
